<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>城市月度温度对比 | WeatherViz Pro</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: #4CAF50;
            --secondary-color: #2196F3;
            --accent-color: #F44336;
            --background-color: #f9f9f9;
            --card-color: #ffffff;
            --text-color: #333333;
            --light-text: #666666;
            --border-color: #eeeeee;
            --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            --radius: 8px;
            --primary-gradient: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: var(--background-color);
            color: var(--text-color);
            line-height: 1.6;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: var(--card-color);
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            overflow: hidden;
            position: relative;
        }

        header {
            background: var(--primary-gradient);
            color: white;
            padding: 20px 30px;
            position: relative;
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .page-title {
            font-size: 24px;
            font-weight: 600;
        }

        .home-button {
            display: inline-flex;
            align-items: center;
            padding: 8px 16px;
            background-color: rgba(255, 255, 255, 0.2);
            color: white;
            text-decoration: none;
            border-radius: 4px;
            transition: background-color 0.3s;
            font-size: 14px;
        }

        .home-button:hover {
            background-color: rgba(255, 255, 255, 0.3);
        }

        .home-button i {
            margin-right: 6px;
        }

        .controls {
            padding: 20px 30px;
            border-bottom: 1px solid var(--border-color);
        }

        .control-group {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            margin-bottom: 20px;
            justify-content: center;
        }

        .control-item {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }

        label {
            font-weight: 500;
            min-width: 80px;
            margin-right: 10px;
            color: var(--text-color);
            font-size: 16px;
        }

        select {
            padding: 10px 15px;
            font-size: 16px;
            border: 1px solid #ddd;
            border-radius: var(--radius);
            min-width: 200px;
            transition: border-color 0.3s, box-shadow 0.3s;
        }

        select:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
        }

        .temp-type-toggle {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin: 20px 0;
            flex-wrap: wrap;
        }

        .temp-type-btn {
            padding: 10px 20px;
            background-color: #f1f1f1;
            border: none;
            border-radius: var(--radius);
            cursor: pointer;
            transition: all 0.3s;
            font-size: 16px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 6px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .temp-type-btn.active {
            background: var(--primary-gradient);
            color: white;
            box-shadow: 0 4px 8px rgba(76, 175, 80, 0.2);
        }

        .temp-type-btn:hover:not(.active) {
            background-color: #e0e0e0;
        }

        .temp-type-btn i {
            font-size: 14px;
        }

        .chart-container {
            padding: 20px 30px;
        }

        #radarChart {
            width: 100%;
            height: 550px;
            background-color: white;
            border-radius: var(--radius);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }

        .placeholder {
            text-align: center;
            padding: 100px 0;
            color: var(--light-text);
            font-size: 18px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
        }

        .placeholder i {
            font-size: 48px;
            color: #ddd;
            margin-bottom: 15px;
        }

        @media (max-width: 768px) {
            .control-group {
                flex-direction: column;
                align-items: center;
            }

            .control-item {
                width: 100%;
                justify-content: center;
            }

            label {
                min-width: 100px;
            }

            #radarChart {
                height: 450px;
            }
        }

        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s, visibility 0.3s;
        }

        .loading-overlay.active {
            opacity: 1;
            visibility: visible;
        }

        .loading-spinner {
            width: 40px;
            height: 40px;
            border: 4px solid rgba(76, 175, 80, 0.1);
            border-left-color: var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div class="header-content">
                <h1 class="page-title">城市月度温度对比雷达图</h1>
            </div>
        </header>

        <div class="controls">
            <div class="control-group">
                <div class="control-item">
                    <label for="citySelect">城市:</label>
                    <select id="citySelect">
                        <option value="">-- 请选择城市 --</option>
                    </select>
                </div>
                <div class="control-item">
                    <label for="yearSelect">年份:</label>
                    <select id="yearSelect">
                        <option value="all">-- 全部年份 --</option>
                    </select>
                </div>
            </div>

            <div class="temp-type-toggle">
                <button class="temp-type-btn" id="btnHigh">
                    <i class="fas fa-temperature-high"></i> 最高温度
                </button>
                <button class="temp-type-btn" id="btnLow">
                    <i class="fas fa-temperature-low"></i> 最低温度
                </button>
                <button class="temp-type-btn active" id="btnBoth">
                    <i class="fas fa-exchange-alt"></i> 双温对比
                </button>
            </div>
        </div>

        <div class="chart-container">
            <div id="radarChart">
                <div class="placeholder">
                    <i class="fas fa-chart-radar"></i>
                    <p>请选择城市和年份</p>
                </div>
            </div>
        </div>
    </div>

    <div class="loading-overlay" id="loadingOverlay">
        <div class="loading-spinner"></div>
    </div>

    <script>
        // 动态加载城市和年份到选择器中
        function loadCitiesAndYears() {
            showLoading(true);

            // 并行获取城市和年份数据，使用正确的API路径
            Promise.all([
                fetch('/menu/api/cities'),
                fetch('/menu/api/years')
            ])
            .then(responses => Promise.all(responses.map(res => res.json())))
            .then(([citiesData, yearsData]) => {
                const citySelect = document.getElementById('citySelect');
                citiesData.cities.forEach((city, index) => {
                    const option = document.createElement('option');
                    option.value = city;
                    option.textContent = city;
                    citySelect.appendChild(option);

                    // 设置默认城市为第一个城市
                    if (index === 0 && citySelect.options.length > 1) {
                        option.selected = true;
                    }
                });

                const yearSelect = document.getElementById('yearSelect');
                yearsData.years.forEach((year, index) => {
                    const option = document.createElement('option');
                    option.value = year;
                    option.textContent = year;
                    yearSelect.appendChild(option);

                    // 设置默认年份为最近一年（数组中的第一个元素）
                    if (index === 0) {
                        option.selected = true;
                    }
                });
            })
            .catch(error => {
                console.error('加载城市或年份数据失败:', error);
                showError('数据加载失败，请刷新页面重试');
            })
            .finally(() => showLoading(false));
        }

        // 城市年份温度数据缓存
        let cityYearData = {
            high: {},  // 最高温度数据
            low: {}    // 最低温度数据
        };

        // 初始化图表
        const chartDom = document.getElementById('radarChart');
        let myChart = null;

        // 月份标签
        const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        const colorList = {
            high: '#F44336',  // 最高温度颜色（红色）
            low: '#2196F3',   // 最低温度颜色（蓝色）
            both: ['#F44336', '#2196F3']  // 双温对比颜色
        };

        // 当前温度类型（high, low, both）
        let currentTempType = 'both';

        // 加载指示器和错误提示
        const loadingOverlay = document.getElementById('loadingOverlay');
        const errorToast = document.createElement('div');
        errorToast.id = 'errorToast';
        errorToast.className = 'fixed top-4 right-4 bg-red-500 text-white py-2 px-4 rounded shadow-lg z-50 transform translate-x-full transition-transform duration-300';
        document.body.appendChild(errorToast);

        function showLoading(show) {
            if (show) {
                loadingOverlay.classList.add('active');
            } else {
                loadingOverlay.classList.remove('active');
            }
        }

        function showError(message) {
            const toast = document.getElementById('errorToast');
            toast.textContent = message;
            toast.classList.remove('translate-x-full');

            setTimeout(() => {
                toast.classList.add('translate-x-full');
            }, 5000);
        }

        // 筛选器变化事件
        document.getElementById('citySelect').addEventListener('change', updateChart);
        document.getElementById('yearSelect').addEventListener('change', updateChart);

        // 温度类型按钮事件
        document.getElementById('btnHigh').addEventListener('click', () => setTempType('high'));
        document.getElementById('btnLow').addEventListener('click', () => setTempType('low'));
        document.getElementById('btnBoth').addEventListener('click', () => setTempType('both'));

        // 设置温度类型
        function setTempType(type) {
            if (currentTempType === type) return;

            // 更新按钮状态
            document.querySelectorAll('.temp-type-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            document.getElementById(`btn${type.charAt(0).toUpperCase() + type.slice(1)}`).classList.add('active');

            currentTempType = type;
            updateChart();
        }

        // 更新图表函数
        async function updateChart() {
            showLoading(true);

            const city = document.getElementById('citySelect').value;
            const year = document.getElementById('yearSelect').value;
            const radarContainer = document.getElementById('radarChart');

            if (!city || (year !== "all" && !year)) {
                radarContainer.innerHTML = '<div class="placeholder"><i class="fas fa-chart-radar"></i><p>请选择城市和年份</p></div>';
                if (myChart) {
                    myChart.dispose();
                    myChart = null;
                }
                showLoading(false);
                return;
            }

            // 如果没有该城市的温度数据，则获取并存储
            const neededTypes = currentTempType === 'both' ? ['high', 'low'] : [currentTempType];
            const fetchPromises = neededTypes.map(type => {
                if (!cityYearData[type][city]) {
                    return fetchCityYearData(city, type);
                }
                return Promise.resolve();
            });

            await Promise.all(fetchPromises);

            // 获取筛选后的数据
            let chartData = [];
            let legendData = [];

            // 处理最高温度
            if (currentTempType === 'high' || currentTempType === 'both') {
                if (year === "all") {
                    // 全部年份模式
                    for (const [y, temps] of Object.entries(cityYearData.high[city] || {})) {
                        if (temps && temps.length === 12) {
                            chartData.push({
                                name: y + '年最高温',
                                value: temps,
                                type: 'high'
                            });
                            legendData.push(y + '年最高温');
                        }
                    }
                } else {
                    // 单一年份模式
                    const temps = cityYearData.high[city]?.[year];
                    chartData.push({
                        name: year + '年最高温',
                        value: temps || new Array(12).fill(null),
                        type: 'high'
                    });
                    legendData.push(year + '年最高温');
                }
            }

            // 处理最低温度
            if (currentTempType === 'low' || currentTempType === 'both') {
                if (year === "all") {
                    // 全部年份模式
                    for (const [y, temps] of Object.entries(cityYearData.low[city] || {})) {
                        if (temps && temps.length === 12) {
                            chartData.push({
                                name: y + '年最低温',
                                value: temps,
                                type: 'low'
                            });
                            legendData.push(y + '年最低温');
                        }
                    }
                } else {
                    // 单一年份模式
                    const temps = cityYearData.low[city]?.[year];
                    chartData.push({
                        name: year + '年最低温',
                        value: temps || new Array(12).fill(null),
                        type: 'low'
                    });
                    legendData.push(year + '年最低温');
                }
            }

            // 如果没有数据，显示提示
            if (chartData.length === 0) {
                radarContainer.innerHTML = '<div class="placeholder"><i class="fas fa-exclamation-circle"></i><p>暂无该城市温度数据</p></div>';
                if (myChart) {
                    myChart.dispose();
                    myChart = null;
                }
                showLoading(false);
                return;
            }

            // 初始化或清除现有图表
            if (!myChart) {
                radarContainer.innerHTML = '';
                myChart = echarts.init(radarContainer);
            }

            // 设置图表配置
            myChart.setOption(getRadarOption(city, chartData, legendData), true);

            // 响应窗口大小变化
            window.addEventListener('resize', function () {
                myChart.resize();
            });

            showLoading(false);
        }

        // 获取选定城市的数据
        async function fetchCityYearData(city, type) {
            showLoading(true);

            const endpoint = type === 'high' ? '/menu/monthly_high_temperature' : '/menu/monthly_low_temperature';
            try {
                const response = await fetch(`${endpoint}?urban=${encodeURIComponent(city)}`);
                const data = await response.json();

                // 处理后端返回的错误信息
                if (data.error || data.message) {
                    showError(data.error || data.message);
                    return;
                }

                if (!cityYearData[type][city]) cityYearData[type][city] = {};

                data.months.forEach((month, index) => {
                    const year = month.split('-')[0];
                    if (!cityYearData[type][city][year]) cityYearData[type][city][year] = new Array(12).fill(null);
                    const monthIndex = parseInt(month.split('-')[1]) - 1; // 转换为0-11的索引
                    const tempKey = type === 'high' ? 'high_temps' : 'low_temps';

                    // 增加数据有效性检查，确保温度数据为数字
                    const tempValue = data[tempKey][index];
                    if (tempValue !== null && !isNaN(tempValue)) {
                        cityYearData[type][city][year][monthIndex] = parseFloat(tempValue);
                    } else {
                        cityYearData[type][city][year][monthIndex] = null;
                        console.warn(`温度数据异常，城市: ${city}, 年份: ${year}, 月份: ${month}, 温度: ${tempValue}`);
                    }
                });
            } catch (error) {
                console.error(`获取${type === 'high' ? '最高' : '最低'}温度数据失败:`, error);
                showError('获取温度数据失败，请稍后重试');
            } finally {
                showLoading(false);
            }
        }

        // 雷达图配置函数
        function getRadarOption(city, chartData, legendData) {
            // 计算最大和最小温度用于动态调整刻度，增加边界值处理
            const allTemps = chartData.flatMap(d => d.value).filter(v => v !== null && !isNaN(v));
            const maxTemp = allTemps.length > 0 ? Math.max(...allTemps) + 5 : 40;
            const minTemp = allTemps.length > 0 ? Math.min(...allTemps) - 5 : -15;

            // 为每个数据项分配颜色
            const coloredData = chartData.map((data, idx) => {
                const color = data.type === 'high' ? colorList.high : colorList.low;
                return {
                    ...data,
                    color
                };
            });

            return {
                backgroundColor: 'transparent',
                title: {
                    text: city + '月度温度对比',
                    subtext: legendData.length > 1 ? '多年份对比' : '单一年份数据',
                    left: 'center',
                    textStyle: {
                        fontSize: 18,
                        color: '#333',
                        fontWeight: 600
                    },
                    subtextStyle: {
                        fontSize: 14,
                        color: '#666'
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        return params.seriesName + '<br/>' + params.name + ':' +
                               (params.value !== null && !isNaN(params.value) ?
                                params.value.toFixed(1) + '°C' : '无有效温度数据');
                    }
                },
                legend: {
                    data: legendData,
                    right: 10,
                    top: 10,
                    icon: 'circle',
                    itemGap: 10,
                    textStyle: { fontSize: 12 }
                },
                radar: {
                    shape: 'circle',
                    center: ['50%', '50%'],
                    radius: ['20%', '80%'],
                    indicator: months.map((month, idx) => ({
                        name: month,
                        max: maxTemp,
                        min: minTemp,
                        label: {
                            formatter: month,
                            color: '#333',
                            fontSize: 12,
                            fontWeight: 'normal',
                            rotate: idx % 2 === 0 ? 0 : 45
                        }
                    })),
                    splitArea: {
                        show: true,
                        areaStyle: {
                            color: ['rgba(245, 245, 245, 0.5)', 'rgba(245, 245, 245, 0.2)']
                        }
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'rgba(200, 200, 200, 0.5)'
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: 'rgba(200, 200, 200, 0.3)'
                        }
                    }
                },
                animation: true,
                animationDuration: 1000,
                animationEasing: 'cubicOut',
                series: [{
                    name: '温度',
                    type: 'radar',
                    data: coloredData.map((data, idx) => ({
                        value: data.value.map(v => v !== null && !isNaN(v) ? v : null), // 过滤无效数据
                        name: data.name,
                        areaStyle: {
                            color: data.color + '33'
                        },
                        lineStyle: {
                            width: 2,
                            color: data.color
                        },
                        symbolSize: 6,
                        label: {
                            show: true,
                            formatter: function (params) {
                                return params.value !== null && !isNaN(params.value) ?
                                       params.value.toFixed(1) + '°C' : '';
                            }
                        }
                    }))
                }]
            };
        }

        // 初始化时加载城市和年份，并自动更新图表
        window.onload = function () {
            loadCitiesAndYears();

            // 延迟调用updateChart，确保城市和年份已加载完成
            setTimeout(() => {
                updateChart();
            }, 500);
        };
    </script>
</body>
</html>